<?php

class MenusAction extends fvAction {
    
    function __construct () {
        parent::__construct(fvSite::$Layoult);
    }

    function executeIndex() {
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_NO_LAYOULT;
        else return self::$FV_OK;
    }
    
    function executeEdit() {
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }
    
    function executeSave() {
        $request = fvRequest::getInstance();
        
        if (!$Menu = MenuManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $Menu = new Menu();
        }
        $mn = $request->getRequestParameter('mn');
        
        if ($Menu->isNew()) {
            $mn['menu_order'] = MenuManager::getInstance()->getCount('parent_id = ?', array($mn['parent_id']));
        }
        
        if (!$Menu->isNew() && ($mn['image'] != '') && ($mn['image'] != $Menu['image'])) {
            $Menu->deleteImages('image');
        }
        
        $Menu->updateFromRequest($mn);
        
        if ($Menu->save()) {
            
            if ($mn['image'] != '') {
                $Menu->saveUploadFile('image', fvSite::$fvConfig->get('path.upload.tmp_dir') . $mn['image']);
            }
             
            fvResponce::getInstance()->setHeader('Id', $Menu->getPk());
            $this->setFlash("Данные успешно сохранены", self::$FLASH_SUCCESS);
            fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/?id=". $Menu->getPk());        
        } else { 
            fvResponce::getInstance()->setHeader('X-JSON', json_encode($Menu->getValidationResult()));
            $this->setFlash("Ошибка при сохранении данных проверте правильность введенных данных", self::$FLASH_ERROR);
        }
        
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }

    private function getObjectById($array, $id) {
        foreach ($array as $key => $object) {
            if ($object->getPk() == $id) return $key;
        }
        return -1;
    }
    
    function executeReorder() {
        
        $Menus = MenuManager::getInstance()->getAll();
        
        $sortableOrder = fvRequest::getInstance()->getRequestParameter("sortables");
        
        foreach ($sortableOrder as $menuOrder => $menuContent) {
            $menuId = $menuContent['id'];
            if (($menuKey = $this->getObjectById($Menus, $menuId)) != -1) {
                $Menus[$menuKey]->parent_id = 0;
                $Menus[$menuKey]->menu_order = $menuOrder;
            }
            if (count($menuContent) > 1) {
                $parentId = $menuContent['id'];
                unset($menuContent['id']);
                foreach ($menuContent as $menuOrder => $menuSubContent) {
                    $menuId = $menuSubContent['id'];
                    if (($menuKey = $this->getObjectById($Menus, $menuId)) != -1) {
                        $Menus[$menuKey]->parent_id = $parentId;
                        $Menus[$menuKey]->menu_order = $menuOrder;
                    }
                }
            }
        }
        
        foreach ($Menus as $menu) {
            $menu->save(false);
        }
        
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }

    function executeDelete() {
        $request = fvRequest::getInstance();
        if (!$Menu = MenuManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
        } else {
            $Menu->delete();
            $this->setFlash("Данные успешно удалены", self::$FLASH_SUCCESS);
        }
        
        fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/");
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_NO_LAYOULT;
        else return self::$FV_OK;
    }
    
    function executeUploadimage () {
        
        $r = fvRequest::getInstance();
        
        if ($r->isFileUpload('image') && ($r->checkUploadFile('image') == fvRequest::ERROR_SUCCESS)) {
            $tmp_dir = fvSite::$fvConfig->get('path.upload.tmp_dir');
            $fileName = $r->getUploadFileName('image');
            $r->saveUploadData('image', $tmp_dir . $fileName);

            fvParams::getInstance()->setParameter(fvRoute::getInstance()->getModuleName() . "/filename", $fileName);
        }

        return self::$FV_AJAX_CALL;
    }

    function executeDeleteImage () {
        $Menu = MenuManager::getInstance()->getByPk(fvRequest::getInstance()->getRequestParameter('id'));
        
        if (!is_object($Menu) || $Menu['image'] != fvRequest::getInstance()->getRequestParameter('image')) {
            if (is_object($Menu) && $Menu->hasFile('image', Menu::IMAGE_TYPE_SMALL)) {
                fvResponce::getInstance()->setHeader('X-JSON', json_encode(
                    array(
                        'image' => $Menu->getImageDir(true) . $Menu->getImageName('image', Menu::IMAGE_TYPE_SMALL),
                        'width' => $Menu->getImageSize(Menu::IMAGE_TYPE_SMALL, Menu::IMAGE_WIDTH),
                        'height' => $Menu->getImageSize(Menu::IMAGE_TYPE_SMALL, Menu::IMAGE_HEIGHT),
                    )
                ));
            }
            if (is_file(fvSite::$fvConfig->get('path.upload.tmp_name').fvRequest::getInstance()->getRequestParameter('image'))) {
                unlink(fvSite::$fvConfig->get('path.upload.tmp_name').fvRequest::getInstance()->getRequestParameter('image'));
            }
        } else {
            if (is_file(fvSite::$fvConfig->get('path.upload.tmp_name').$Menu['image'])) {
                unlink(fvSite::$fvConfig->get('path.upload.tmp_name').$Menu['image']);
            }
            $Menu->deleteImages('image');
        }
        
        $this->setFlash("Изображение успешно удалено", fvAction::$FLASH_SUCCESS);
        
        return self::$FV_AJAX_CALL;
    }
}

?>
